package com.atguigu.chapter05.sink;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.connector.jdbc.JdbcConnectionOptions;
import org.apache.flink.connector.jdbc.JdbcExecutionOptions;
import org.apache.flink.connector.jdbc.JdbcSink;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.http.HttpHost;

import java.util.ArrayList;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/6/10 10:09
 */
public class Flink04_Sink_JDBC {
    public static void main(String[] args) throws Exception {
        
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment().setParallelism(1);
        
        ArrayList<HttpHost> hosts = new ArrayList<>();
        hosts.add(new HttpHost("hadoop162", 9200));
        hosts.add(new HttpHost("hadoop163", 9200));
        hosts.add(new HttpHost("hadoop164", 9200));
        String sql = "replace into sensor(id, ts, vc) values(?,?,?)";
        env
            .socketTextStream("hadoop162", 9999)
            .map(new MapFunction<String, WaterSensor>() {
                @Override
                public WaterSensor map(String line) throws Exception {
                    String[] data = line.split(",");
                    return new WaterSensor(data[0], Long.valueOf(data[1]), Integer.valueOf(data[2]));
                }
            })
            .keyBy(WaterSensor::getId)
            .sum("vc")
            .addSink(JdbcSink.sink(sql,
                                   (ps, ws) -> {
                                       // 只需要替换占位符即可,其他的什么都不要做
                                       ps.setString(1, ws.getId());
                                       ps.setLong(2, ws.getTs());
                                       ps.setInt(3, ws.getVc());
                                   },
                                   JdbcExecutionOptions.builder()
                                       .withMaxRetries(3)
                                       .withBatchIntervalMs(2)
                                       .build(),
                                   new JdbcConnectionOptions.JdbcConnectionOptionsBuilder()
                                       .withDriverName("com.mysql.jdbc.Driver")
                                       .withUrl("jdbc:mysql://hadoop162:3306/test?useSSL=false")
                                       .withUsername("root")
                                       .withPassword("aaaaaa")
                                       .build()
            ));
        
        env.execute();
        
    }
    
}
